const { Sequelize } = require("sequelize");
const path = require("path");
const mysql = require("mysql2/promise");
// 引入假数据
const { user, userinfo, area, students } = require("./data");
const defineModels = require("./models");

const customPath = path.resolve(process.cwd(), `.env.${process.env.NODE_ENV}`);
require("dotenv").config({ path: customPath });

const dbName = process.env.DATA_BASE;
const username = process.env.DATA_BASE_USER;
const password = process.env.DATA_BASE_PASSWORD;
const host = process.env.DATA_BASE_HOST;

async function insertAreaData(area, Area, parentCode = null) {
    for (let data of area) {
        await Area.create({
            code: data.code,
            value: data.value,
            parentCode,
        });
        if (data.children) {
            await insertAreaData(data.children, Area, data.code);
        }
    }
}

// 创建并插入数据的操作
async function createDatabase() {
    const connection = await mysql.createConnection({
        host: host,
        user: username,
        password: password,
    });
    await connection.query(`CREATE DATABASE IF NOT EXISTS ${dbName}`);
    await connection.end();

    // 插入数据使用Sequelize
    const sequelize = new Sequelize(dbName, username, password, {
        host,
        dialect: process.env.DIALECT,
        dialectModule: require(process.env.DIALECT_MODULE),
    });
    const { User, UserInfo, Area, Student } = defineModels(sequelize);

    await sequelize.sync({ force: true });
    await User.create(user);
    await UserInfo.bulkCreate(userinfo);
    await Student.bulkCreate(students);
    await insertAreaData(area, Area, null);
    console.log("Database and tables created, data inserted.");
}

async function clearDatabase() {
    const connection = await mysql.createConnection({
        host: host,
        user: username,
        password: password,
    });
    await connection.query(`DROP DATABASE IF EXISTS ${dbName}`);
    await connection.end();
    console.log("Database dropped.");
}

const command = process.argv[2];
if (command === "create") {
    // 负责播种（构建假数据，真实数据没有构建时，后端程序员自己构建）
    createDatabase().catch((error) => console.log(error));
} else if (command === "clear") {
    // 负责清理（销毁假数据，真实数据已有, 清除假数据）
    clearDatabase().catch((error) => console.log(error));
} else {
    console.log("Invalid command. Please user 'create' or 'clear'");
}
